package org.ct.gui.buttons;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import org.ct.dataobjects.Student;
import org.ct.utils.HibernateUtils;
import org.ct.utils.InfoDialogs;

@SuppressWarnings("serial")
public class AddStudentButton extends JButton {
	private final JTextField idField, firstNameField, surnameField;

	public AddStudentButton(String text, JTextField idField, JTextField firstNameField, JTextField surnameField) {
		super(text);
		this.idField = idField;
		this.firstNameField = firstNameField;
		this.surnameField = surnameField;
		this.addActionListener(new ClickListener());
	}

	class ClickListener implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent action) {
			Integer id;
			try {
				String idString = idField.getText();
				id = Integer.parseInt(idString);
			} catch (NumberFormatException e) {
				JOptionPane.showMessageDialog(null, "Id must be an integer", "Error", JOptionPane.ERROR_MESSAGE);
				return;
			}

			String firstNameString = firstNameField.getText();
			String surnameString = surnameField.getText();

			Student student = new Student(id, firstNameString, surnameString);

			try {
				HibernateUtils.addNewStudentWithIdCollisionCheck(student);
			} catch (IllegalArgumentException e) {
				InfoDialogs.showError(e);
			}

		}
	}
}
